package com.sy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.blog.dao.mapper.TagMapper;
import com.sy.blog.dao.pojo.Tag;
import com.sy.blog.service.TagService;
import com.sy.blog.vo.Result;
import com.sy.blog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    public TagVo copy(Tag tag){
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag,tagVo);
        tagVo.setId(String.valueOf(tag.getId()));
        return tagVo;
    }
    public List<TagVo> copyList(List<Tag> tagList){
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }

    /**
     * Mybatis-Plus无法多表查询，所以要自定义mapper中的方法
     * @param articleId
     * @return
     */
    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        return copyList(tags);
    }

    /**
     * 询出使用标签最多的前6个标签的id，再根据标签的id查询出标签的名称
     * @param limit
     * @return
     */
    @Override
    public Result findHotTagsByTagId(int limit) {
        List<Long> hotIds = tagMapper.findHotTagsId(limit);
        List<Tag> hotTags = tagMapper.findHotTagsByTagIds(hotIds);
        return Result.success(hotTags);
    }


    @Override
    public Result findAll() {
        LambdaQueryWrapper<Tag> tagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.select(Tag::getId, Tag::getTagName);
        return Result.success(copyList(tagMapper.selectList(tagLambdaQueryWrapper)));
    }

    @Override
    public Result findAllDetail() {
        return Result.success(copyList(tagMapper.selectList(new LambdaQueryWrapper<>())));

    }

    @Override
    public Result findDetailById(Long id) {
        Tag tag = tagMapper.selectById(id);
        return Result.success(copy(tag));
    }
}
